import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:projectfluttershengyihuatong/AllControllerBinding.dart';
import 'package:projectfluttershengyihuatong/category/category.dart';
import 'package:projectfluttershengyihuatong/login/login.dart';
import 'package:projectfluttershengyihuatong/service/loginService/logginservice.dart';
import 'package:projectfluttershengyihuatong/service/request_manager.dart';
import 'package:projectfluttershengyihuatong/tool/tool.dart';
import 'category/catetory_controller.dart';
import 'service/launchservice/launchservice.dart';
import 'package:get/get.dart';
import 'route.dart';
import 'tabbar/tabbar_manager.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

Future<void> openSettings() async {
  // 对于Android设备，使用'app_settings'来打开应用设置页面
  if (Platform.isAndroid) {
    await launchUrl(Uri.parse('app_settings:'));
  }

  // 对于iOS设备，没有直接的方式打开设置页面，但可以打开应用的权限设置页面
  if (Platform.isIOS) {
    // 打开应用的权限设置，这里以相机为例
    await launchUrl(Uri.parse('App-Settings:'));
  }
}
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final result =  await RequestManager.checkAndRequestNetworkPermission();
  print(result);
  if (result){
    runApp(const MyApp());

  }else {
    runApp(MaterialApp(
      home: Scaffold(
        body: Directionality(
          textDirection: TextDirection.ltr,
          child: Container(
            child: GestureDetector(
              child: const Center(
                child: Text("点击跳转到设置页面开启网络"),
              ),
              onTap: ()async{
                await openSettings();
              },
            ),
          ),
        ),
      ),
    ));
  }
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      navigatorKey: NavKey.navigatorKey,
      initialBinding: AllControllerBinding(),
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a blue toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      initialRoute: "/",
      getPages: pages,
      home: const MyHomePage(
        title: "",
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Get.find<LoginService>().getUserInfo();
    Get.find<CatetoryController>().getSaveCatetory();
  }



  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      body: GetBuilder<LaunchService>(
        id: LaunchService.appConfig,
        builder: (controller){
          if (controller.config.api == null) {
            return GestureDetector(
              child: const Center(
                child: Text("app报错，没有请求到数据,点击冲洗请求"),
              ),
              onTap: (){
                LaunchService.requestConfig();
              },

            );
          }else {
            return GetBuilder<LoginService>(
                id: LoginService.LOGIN,
                builder: (loginController){
              if (loginController.userInfo == null) {
                return const Login(type: 2,);
              }else {
                return GetBuilder<CatetoryController>(id: CatetoryController.leiCategory,builder: (categoryController){
                  if (categoryController.leiModel == null) {
                    return CategoryPage(pageType: 1,);
                  }else {
                    return TabbarManager();
                  }
                });
              }

            });
          }
        },
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

  }
}
